<template>
  <div class="login-page">
    <validate-form @form-submit="onSubmitForm">
      <div class="mb-3">
        <label class="form-label">Email address</label>
        <validate-input :rules="emailRules" v-model="emailVal" placeholder="请输入邮箱地址"></validate-input>
      </div>
      <div class="mb-3">
        <label class="form-label">Password</label>
        <validate-input :rules="passwordRules" v-model="passwordVal" placeholder="请输入密码" type="password"></validate-input>
      </div>
      <!-- <button type="submit" class="btn btn-primary">Submit</button> -->
      <template #submit>
        <!-- <span class="btn btn-danger">Submit</span> -->
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import ValidateInput, { RulesProp } from './../components/ValidateInput.vue'
import ValidateForm from './../components/ValidateForm.vue'
import CreateMessage from './../components/CreateMessage'
export default defineComponent({
  name: 'login',
  components: {
    ValidateForm,
    ValidateInput
  },
  setup () {
    const router = useRouter()
    const store = useStore()
    const emailRules: RulesProp = [
      { type: 'required', message: '电子邮箱地址不能为空' },
      { type: 'email', message: '请输入正确的电子邮箱格式' }
    ]
    const passwordRules: RulesProp = [
      { type: 'required', message: '密码不能为空' },
      { type: 'minLength', message: '密码至少为6位数' },
      { type: 'maxLength', message: '密码最多不能超过20位数' }
    ]
    // reactive 响应式api 返回对象的响应式副本
    const emailVal = ref('')
    const passwordVal = ref('')
    const onSubmitForm = (result: boolean) => {
      if (result) {
        const payload = {
          email: emailVal.value,
          password: passwordVal.value
        }
        store.dispatch('loginAndFetch', payload).then(() => {
          CreateMessage('登录成功，两秒后跳转', 'success', 2000)
          setTimeout(() => {
            router.push({ name: 'home' })
          }, 2000)
        }).catch(e => {
          console.log(e)
        })
      }
    }
    return {
      emailRules,
      passwordRules,
      emailVal,
      passwordVal,
      onSubmitForm
    }
  }
})
</script>
